package SHU.water2;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.base.Lang;
import com.qweather.sdk.bean.base.Unit;
import com.qweather.sdk.bean.weather.WeatherDailyBean;
import com.qweather.sdk.view.HeConfig;
import com.qweather.sdk.view.QWeather;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import Secondpagh.abook;
import Secondpagh.fix;
import Secondpagh.live;
import Secondpagh.set;
import Secondpagh.waterLevelChart;
import Secondpagh.waterWarning;
import Secondpagh.pumpMap;
import Secondpagh.eqMaintenance;
import Secondpagh.waterQuality;
import Secondpagh.drainage;
import Secondpagh.rainLevelChart;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int REQUEST_CODE_SCAN_ONE = 0X01;
    private static final int DEFAULT_VIEW = 0X01;
    private View view1,view2;

    public static boolean globals = true;
    public static boolean globalj = true;

    public String weather;
    public String area = "CN101020700";

    public String year;
    public String month;
    public String day;

    @SuppressLint("InflateParams")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImmersionBar.with(this).statusBarColor(R.color.color).fitsSystemWindows(true).init();

        //Bmob.initialize(this, "c6cee79840d64c69a4202ba3b469ec06");
        //startService(new Intent(this, LocalService.class));
        //startService(new Intent(this, RemoteService.class));
        //startService(new Intent(this, JobSchedulerService.class));

        //初始化和风帐号
        HeConfig.init("HE2012241604121502", "b5145c8cac5049e1bbbd876276871dc5");
        HeConfig.switchToDevService();

        ViewPager mviewPager2 = findViewById(R.id.viewpager2);

        LayoutInflater mLi = LayoutInflater.from(this);
        view1 = mLi.inflate(R.layout.vieepage1, null);
        view2 = mLi.inflate(R.layout.viewpage2, null);

        //初始化并监听各个按钮对应界面
        click();

        List<View> list = new ArrayList<>();
        list.add(view1);
        list.add(view2);

        final ArrayList<View> views = new ArrayList<View>();
        views.add(view1);
        views.add(view2);

//        mviewPager2.setAdapter(new ViewPagerAdapter(this, list, mviewPager2));
        PagerAdapter mPagerAdapter = new PagerAdapter() {

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            @Override
            public int getCount() {
                return views.size();
            }

            @Override
            public void destroyItem(@NotNull View container, int position, @NotNull Object object) {
                ((ViewPager) container).removeView(views.get(position));
            }


            @NotNull
            @Override
            public Object instantiateItem(@NotNull View container, int position) {
                ((ViewPager) container).addView(views.get(position));
                return views.get(position);
            }
        };

        mviewPager2.setAdapter(mPagerAdapter);

        //天气预报
        show();

        nfcCheck();


        onNewIntent(getIntent());

    }


    //调用系统返回指令后，程序后台进行，防止再次登录等操作
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }


    //强制纵屏
    @Override
    protected void onResume() {
        super.onResume();
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

    }

    /*天气展示*/
    public void show() {

        QWeather.getWeather3D(MainActivity.this, area, Lang.ZH_HANS, Unit.METRIC, new QWeather.OnResultWeatherDailyListener() {
            @Override
            public void onError(Throwable e) {
                Log.i("weather", "getWeather onError: " + e);
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(WeatherDailyBean weatherBean) {
                TextView textView3 = findViewById(R.id.textView3);
                TextView textView4 = findViewById(R.id.textView4);
                TextView textView5 = findViewById(R.id.textView5);
                TextView textView6 = findViewById(R.id.textView6);
                TextView textView7 = findViewById(R.id.textView7);
                TextView textView8 = findViewById(R.id.textView8);
                TextView textView9 = findViewById(R.id.textView9);
                TextView textView10 = findViewById(R.id.textView10);
                TextView textView11 = findViewById(R.id.textView11);
                ImageView imageView1 = findViewById(R.id.imageView1);
                ImageView imageView2 = findViewById(R.id.imageView2);
                ImageView imageView3 = findViewById(R.id.imageView3);

                Log.i("weather", "getWeather onSuccess: " + new Gson().toJson(weatherBean));

                if (Code.OK.getCode().equalsIgnoreCase(weatherBean.getCode())) {
                    List<WeatherDailyBean.DailyBean> threeday = weatherBean.getDaily();

                    year = threeday.get(0).getFxDate().substring(0, 4);
                    month = threeday.get(0).getFxDate().substring(5, 7);
                    day = threeday.get(0).getFxDate().substring(8, 10);
                    textView3.setText(threeday.get(0).getFxDate().substring(5));

                    weather = threeday.get(0).getTextDay();
                    textView4.setText(weather);
                    if (weather.equals("晴"))
                        imageView1.setImageResource(R.mipmap.qingtian);
                    else if (weather.contains("云"))
                        imageView1.setImageResource(R.mipmap.duoyun);
                    else if (weather.contains("阴"))
                        imageView1.setImageResource(R.mipmap.yintian);
                    else if (weather.contains("雨"))
                        imageView1.setImageResource(R.mipmap.yu);
                    else if (weather.contains("雪"))
                        imageView1.setImageResource(R.mipmap.xue);
                    else if (weather.contains("雾"))
                        imageView1.setImageResource(R.mipmap.wu);
                    else if (weather.contains("霾"))
                        imageView1.setImageResource(R.mipmap.mai);
                    textView5.setText(threeday.get(0).getTempMin() + "~" + threeday.get(0).getTempMax() + "℃");

                    textView6.setText(threeday.get(1).getFxDate().substring(5));
                    weather = threeday.get(1).getTextDay();
                    textView7.setText(weather);
                    if (weather.equals("晴"))
                        imageView2.setImageResource(R.mipmap.qingtian);
                    else if (weather.contains("云"))
                        imageView2.setImageResource(R.mipmap.duoyun);
                    else if (weather.contains("阴"))
                        imageView2.setImageResource(R.mipmap.yintian);
                    else if (weather.contains("雨"))
                        imageView2.setImageResource(R.mipmap.yu);
                    else if (weather.contains("雪"))
                        imageView2.setImageResource(R.mipmap.xue);
                    else if (weather.contains("雾"))
                        imageView2.setImageResource(R.mipmap.wu);
                    else if (weather.contains("霾"))
                        imageView2.setImageResource(R.mipmap.mai);
                    textView8.setText(threeday.get(1).getTempMin() + "~" + threeday.get(1).getTempMax() + "℃");

                    textView9.setText(threeday.get(2).getFxDate().substring(5));
                    weather = threeday.get(2).getTextDay();
                    textView10.setText(weather);
                    if (weather.equals("晴"))
                        imageView3.setImageResource(R.mipmap.qingtian);
                    else if (weather.contains("云"))
                        imageView3.setImageResource(R.mipmap.duoyun);
                    else if (weather.contains("阴"))
                        imageView3.setImageResource(R.mipmap.yintian);
                    else if (weather.contains("雨"))
                        imageView3.setImageResource(R.mipmap.yu);
                    else if (weather.contains("雪"))
                        imageView3.setImageResource(R.mipmap.xue);
                    else if (weather.contains("雾"))
                        imageView3.setImageResource(R.mipmap.wu);
                    else if (weather.contains("霾"))
                        imageView3.setImageResource(R.mipmap.mai);
                    textView11.setText(threeday.get(2).getTempMin() + "~" + threeday.get(2).getTempMax() + "℃");
                } else {
                    String status = weatherBean.getCode();
                    Code code = Code.toEnum(status);
                    Log.i("weather", "failed code: " + code);
                }

            }

        });

    }

    private void click() {
        view1.findViewById(R.id.button1).setOnClickListener(this);
        view1.findViewById(R.id.button2).setOnClickListener(this);
        view2.findViewById(R.id.button3).setOnClickListener(this);
        view1.findViewById(R.id.button4).setOnClickListener(this);
        view2.findViewById(R.id.button5).setOnClickListener(this);
        view1.findViewById(R.id.button6).setOnClickListener(this);
        view1.findViewById(R.id.button7).setOnClickListener(this);
        view2.findViewById(R.id.button8).setOnClickListener(this);
        findViewById(R.id.button9).setOnClickListener(this);
        view2.findViewById(R.id.button10).setOnClickListener(this);
        view1.findViewById(R.id.button11).setOnClickListener(this);
        view2.findViewById(R.id.button13).setOnClickListener(this);

    }

    /*点击事件触发*/
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
//
        switch (v.getId()) {
            case R.id.button1:
                //跳转水闸监测
                intent.setClass(getApplicationContext(), pumpMap.class);
                startActivity(intent);
                break;
            case R.id.button2:
                //跳转水位监测
                intent.setClass(getApplicationContext(), waterLevelChart.class);
                startActivity(intent);
                break;
            case R.id.button3:
                //跳转水质监测
                intent.setClass(getApplicationContext(), waterQuality.class);
                startActivity(intent);
                break;
            case R.id.button4:
                //跳转雨量监测
                intent.setClass(getApplicationContext(), rainLevelChart.class);
                startActivity(intent);
                break;
            case R.id.button5:
                //跳转养护设备
                intent.setClass(getApplicationContext(), eqMaintenance.class);
                startActivity(intent);
                break;
            case R.id.button6:
                //跳转
                intent.setClass(getApplicationContext(), fix.class);
                startActivity(intent);
                break;
            case R.id.button7:
                //跳转水位警报
                intent.setClass(getApplicationContext(), waterWarning.class);
                startActivity(intent);
                break;
            case R.id.button8:
                //跳转引排水
                intent.setClass(getApplicationContext(), drainage.class);
                startActivity(intent);
                break;
            case R.id.button9:
                //跳转二维码

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    this.requestPermissions(
                            new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
                            DEFAULT_VIEW);
                }
                break;
            case R.id.button10:
                //跳转设置
                intent.setClass(getApplicationContext(), set.class);
                startActivity(intent);
                break;

            case R.id.button11:
                //跳转在线监控
                intent.setClass(getApplicationContext(), live.class);
                startActivity(intent);
                break;

            case R.id.button13:
                intent.setClass(getApplicationContext(), abook.class);
                startActivity(intent);
                break;
        }

    }

    /*二维码扫描*/
    public void onRequestPermissionsResult(int requestCode, @NotNull String[] permissions, @NotNull int[] grantResults) {
        if (permissions == null || grantResults == null || grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        //申请权限之后，调用DefaultView扫码界面
        ScanUtil.startScan(MainActivity.this, REQUEST_CODE_SCAN_ONE, new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.ALL_SCAN_TYPE).create());
    }

    /*二维码扫描结果*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        if (requestCode == REQUEST_CODE_SCAN_ONE) {
            HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
            String Urit = obj.showResult;

            //Uri uri = Uri.parse(Urit);

            Intent intent = new Intent(getApplicationContext(), fix.class);
            startActivity(intent);
        }
    }

    //@Override
    public void nfcCheck() {
        //super.onStart();
        NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this);//设备的NfcAdapter对象
        if (mNfcAdapter == null) {//判断设备是否支持NFC功能
            //Toast.makeText(this, "设备不支持NFC功能", Toast.LENGTH_SHORT).show();

            AlertDialog.Builder alertDialogbuilder = new AlertDialog.Builder(this);
            alertDialogbuilder.setTitle("提示");
            alertDialogbuilder.setMessage("设备不支持NFC功能");
            alertDialogbuilder.setPositiveButton("确定", null);
            final AlertDialog alertdialog = alertDialogbuilder.create();
            alertdialog.show();
            return;
        }
        if (!mNfcAdapter.isEnabled()) {//判断设备NFC功能是否打开
            //Toast.makeText(this, "请到系统设置中打开NFC功能", Toast.LENGTH_SHORT).show();
            AlertDialog.Builder alertDialogbuilder = new AlertDialog.Builder(this);
            alertDialogbuilder.setTitle("提示");
            alertDialogbuilder.setMessage("请到系统设置中打开NFC功能");
            alertDialogbuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);
                    startActivity(setNfc);
                }
            });
            alertDialogbuilder.setNeutralButton("取消", null);
            final AlertDialog alertdialog = alertDialogbuilder.create();
            alertdialog.show();
        }
    }

}





